﻿using PlugIn;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormPlugin
{
    /// <summary>
    /// 应用程序上下文对象类
    /// 作者：Zuowenjun
    /// 2016-3-26
    /// </summary>
    public class AppContext : IAppContext
    {

        internal static AppContext Current;

        internal Dictionary<string, Type> AppFormTypes
        {
            get;
            set;
        }

        public string AppName
        {
            get;
            private set;
        }

        public string AppVersion
        {
            get;
            private set;
        }

        public object SessionUserInfo
        {
            get;
            private set;
        }

        public object PermissionInfo
        {
            get;
            private set;
        }

        public ConcurrentDictionary<string, object> AppCache
        {
            get;
            private set;
        }

        public System.Windows.Forms.Form AppFormContainer
        {
            get;
            private set;
        }


        public AppContext(string appName, string appVersion, object sessionUserInfo, object permissionInfo, Form appFormContainer)
        {
            this.AppName = appName;
            this.AppVersion = appVersion;
            this.SessionUserInfo = sessionUserInfo;
            this.PermissionInfo = permissionInfo;
            this.AppCache = new ConcurrentDictionary<string, object>();
            this.AppFormContainer = appFormContainer;
        }

        public System.Windows.Forms.Form CreatePlugInForm(Type formType, params object[] args)
        {
            if (this.AppFormTypes.ContainsValue(formType))
            {
                return Activator.CreateInstance(formType, args) as Form;
            }
            else
            {
                throw new ArgumentOutOfRangeException(string.Format("该窗体类型{0}不在任何一个模块组件窗体类型注册列表中！", formType.FullName), "formType");
            }
        }

        public System.Windows.Forms.Form CreatePlugInForm(string formTypeName, params object[] args)
        {
            if (!formTypeName.Contains('.'))
            {
                formTypeName = "." + formTypeName;
            }
            var formTypes = this.AppFormTypes.Where(t => t.Key.EndsWith(formTypeName, StringComparison.OrdinalIgnoreCase)).ToArray();
            if (formTypes == null || formTypes.Length != 1)
            {
                throw new ArgumentException(string.Format("从窗体类型注册列表中未能找到与【{0}】相匹配的唯一窗体类型!", formTypeName), "formTypeName");
            }
            return CreatePlugInForm(formTypes[0].Value, args);
        }


        public Form CreatePlugInForm<TForm>(params object[] args) where TForm : Form
        {
            return CreatePlugInForm(typeof(TForm), args);
        }
    }
}
